<template>
  <div style="padding: 10px">
    <!-- 功能区域 -->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="add">新增</el-button>
      <el-button type="primary">导入</el-button>
      <el-button type="primary">导出</el-button>
    </div>
    <!-- 搜索区域 -->
    <div style="margin: 10px 0">
      <el-input
        v-model="search"
        placeholder="Please input"
        style="width: 20%"
        clearable
      />
      <el-button type="primary" style="margin-left: 5px" @click="load"
        >查询</el-button
      >
    </div>

    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" sortable />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="time" label="发布时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="mini" @click="details(scope.row)"> 详情 </el-button>
          <el-button size="mini" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-popconfirm
            title="确认删除嘛?"
            @confirm="handleDelete(scope.row.id)"
          >
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">
      <el-pagination
        v-model:currentPage="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>

      <el-dialog v-model="dialogVisible" :title="dialog_title" width="80%">
        <el-form ref="form" v-model="form" label-width="120px">
          <el-form-item label="标题">
            <el-input v-model="form.title" style="width: 80%"></el-input>
          </el-form-item>

          <div id="div1"></div>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="save">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog v-model="dialogDetailVisible" title="详情" width="80%">
        <el-card>
          <div v-html="detail.content" style="min-height: 100px"></div>
        </el-card>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import { InfoFilled } from "@element-plus/icons-vue";
import request from "@/utils/request";
import E from "wangeditor";
let editor;
export default {
  name: "News",
  components: {
    InfoFilled,
  },
  data() {
    return {
      // 搜索框
      search: "",
      // 表格属性
      // 当前页
      currentPage: 1,
      // 每页个数
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      form: {},
      tableData: [],
      // 窗格标题
      dialog_title: "tips",
      dialogDetailVisible: false,
      // 接收详情
      detail: {},
    };
  },
  // 页面一加载就调用
  created() {
    this.load();
  },
  methods: {
    // 内容详情
    details(row) {
      if (
        row.content === null ||
        row.content.length === 0 ||
        row.content === ""
      ) {
        this.$message({
          type: "success",
          message: "该新闻无内容",
        });
      } else {
        this.detail = row;
        this.dialogDetailVisible = true;
      }
    },
    load() {
      request
        .get("/news", {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            search: this.search,
          },
        })
        .then((response) => {
          console.log(response);
          this.tableData = response.data.records;
          this.total = response.data.total;
        });
    },
    // add: 新增弹出表单
    add() {
      this.dialog_title = "新增新闻";
      this.dialogVisible = true;
      this.form = {};
      this.$nextTick(() => {
        // 存在公有变量 ，新增时一切值为空
        if (!editor) {
          // 关联弹窗里面的div, new 一个 editor 对象
          editor = new E("#div1");
          // 配置 server 接口地址
          editor.config.uploadImgServer =
            "http://localhost:9091/files/editor/upload";
          // 设置上传参数名称
          editor.config.uploadFileName = "file";
          editor.create();
        }
        editor.txt.html("");
      });
    },
    save() {
      // 接收编辑框的内容，然后赋值
      this.form.content = editor.txt.html();
      // 如果id 存在，更新操作，否则新增
      if (this.form.id) {
        request.put("/news", this.form).then((response) => {
          console.log(response);
          if (response.result == "SUCCESS") {
            this.$message({
              type: "success",
              message: "更新成功",
            });
          } else {
            this.$message({
              type: "error",
              message: response.message,
            });
          }
        });
      } else {
        // 获取缓存信息，昵称信息赋值给新闻的编写者
        let consumerStr = sessionStorage.getItem("consumer") || "{}";
        let consumer = JSON.parse(consumerStr);
        this.form.author = consumer.nickName;
        request.post("/news", this.form).then((response) => {
          console.log(response);
          if (response.result == "SUCCESS") {
            this.$message({
              type: "success",
              message: "新增记录成功",
            });
          } else {
            this.$message({
              type: "error",
              message: response.message,
            });
          }
        });
      }
      // 刷新表格数据
      this.load();
      // 关闭弹窗
      this.dialogVisible = false;
    },
    handleEdit(row) {
      // 对选中行对象进行深拷贝
      this.form = JSON.parse(JSON.stringify(row));
      this.dialog_title = "编辑用户信息";
      this.dialogVisible = true;
      this.$nextTick(() => {
        // 关联弹窗里面的div, new 一个 editor 对象
        if (!editor) {
          editor = new E("#div1");
          // 配置 server 接口地址
          editor.config.uploadImgServer =
            "http://localhost:9091/files/editor/upload";
          // 设置上传参数名称
          editor.config.uploadFileName = "file";
          editor.create();
        }
        editor.txt.html(row.content);
      });
    },
    handleDelete(id) {
      console.log(id);
      request.delete("/news/" + id).then((response) => {
        if (response.result == "SUCCESS") {
          this.$message({
            type: "success",
            message: "删除成功",
          });
        } else {
          this.$message({
            type: "error",
            message: response.message,
          });
        }
      });
      // 重新加载表格的数据
      this.load();
    },
    // 改变当前每页的个数 触发
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.load();
    },
    // 改变当前页码触发
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load();
    },
  },
};
</script>
<style lang="scss" scoped></style>
